default_encoding = 'utf-8'
# coding: utf-8
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from rest_framework.decorators import api_view
import json
from myblog.models import DolphinTestRequestTestCase, DolphinTestRequest
from myblog.dolphinService.baseCode import getResonCode
from django.core import serializers
import re
import logging
import math

logger = logging.getLogger('log')
from django.db.models import Q, F


@csrf_exempt  # 允许跨域访问
@api_view(['POST'])
def addInterface(request):  # 新增接口管理
    data = eval(json.loads(request.body)["data"])
    try:
        print(data)
        if (data["request_mode"] != "" and data["request_name"] != "" and data["request_address"] != "" and data[
            "request_group_id"] != ""):
            interface = DolphinTestRequest(request_name=data["request_name"], request_mode=data["request_mode"],
                                           remark=data["remark"], request_group_id=data["request_group_id"],
                                           request_address=data["request_address"], )
            interface.save()
            response = getResonCode().getSuccess()
            return JsonResponse(response)
        else:
            response = getResonCode().getFail()
            response["msg"] = "缺少参数"
            return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


import datetime


@csrf_exempt
@api_view(['POST'])
def getInterface(request):  # 获取查询表.
    data = eval(json.loads(request.body)["data"])
    pageSize = data["pageSize"]
    pageNum = data["pageNum"]
    try:
        groupList = DolphinTestRequest.objects.filter(request_group_id=data["request_group_id"]).order_by(
            "-updata_time")
        groupList = groupList.filter(
            Q(request_name__icontains=data["request_name"]) & Q(request_address__icontains=data["request_address"]) & Q(
                request_mode__icontains=data["request_mode"]))
        gourpSizeList = groupList[:pageSize * pageNum]  # 查询数据
        gourpCount = groupList.count()  # 查询总数
        countNum = math.ceil(gourpCount / pageSize)  # 总页数
        data = json.loads(serializers.serialize("json", gourpSizeList))[
               pageSize * pageNum - pageSize:pageSize * pageNum]
        for i in range(len(data)):
            creatTime = data[i]["fields"]["creat_time"]
            updata_time = data[i]["fields"]["updata_time"]
            data[i]["fields"]["creat_time"] = re.split('[TZ.]', creatTime)[0] + " " + re.split('[TZ.]', creatTime)[1]
            data[i]["fields"]["updata_time"] = re.split('[TZ.]', updata_time)[0] + " " + re.split('[TZ.]', updata_time)[
                1]
        response = getResonCode().getSuccess()
        response["data"] = data
        response["countNum"] = countNum  # 总页数
        response["gourpCount"] = gourpCount  # 总数据量
        response["pageNum"] = pageNum  # 当前页码
        response["pageSize"] = pageSize  # 当前一页多少个数据

        return JsonResponse(response)
    except EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


@csrf_exempt
@api_view(['POST'])
def updateInterface(request):  # 修改接口信息
    data = eval(json.loads(request.body)["data"])
    try:
        print(data)
        if data["interfaceid"] != "" and data["request_name"] != "" and data["request_address"] != "" and data[
            "request_mode"] != "":
            interface = DolphinTestRequest.objects.get(request_id=data["interfaceid"])
            interface.request_name = data["request_name"]
            interface.request_address = data["request_address"]
            interface.request_mode = data["request_mode"]
            interface.remark = data["remark"]
            interface.save()
            response = getResonCode().getSuccess()
            return JsonResponse(response)
        else:
            response = getResonCode().getFail()
            response["msg"] = "缺少参数,或参数为空"
            return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


# DolphinTestGrouping.objects.filter(group_id=data["id"]).update(group_name = data["name"], remark = data["remark"]) #

@csrf_exempt
@api_view(['POST'])
def deleteInterface(request):  # 删除接口信息
    data = eval(json.loads(request.body)["data"])
    try:
        if data["id"] != "":
            dolphinRequest = DolphinTestRequestTestCase.objects.filter(case_request_id=data["id"])
            if len(dolphinRequest) > 0:
                response = getResonCode().getFail()
                response["msg"] = "当前接口中还存在接口用例无法删除"
                return JsonResponse(response)
            if len(dolphinRequest) == 0:
                DolphinTestRequest.objects.filter(request_id=data["id"]).delete()
                response = getResonCode().getSuccess()
                response["msg"] = "删除成功"
                return JsonResponse(response)
        else:
            response = getResonCode().getFail()
            response["msg"] = "缺少参数,或参数为空"
            return JsonResponse(response)
    except  EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)


@csrf_exempt
@api_view(['POST'])
def getRequest(request):  # 获得单个接口列表数据
    data = eval(json.loads(request.body)["data"])
    try:
        groupList = DolphinTestRequest.objects.filter(request_id=data["request_id"])
        data = json.loads(serializers.serialize("json", groupList))
        response = getResonCode().getSuccess()
        response["data"] = data
        return JsonResponse(response)

    except EOFError as e:
        logging.error(e)
        response = getResonCode().getErorr()
        return JsonResponse(response)
